using BasicData.API.Application.Command;
using BasicData.API.Dtos;
using BasicData.API.Services;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 用户注册命令处理器
    /// </summary>
    public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, APIResult<UserDTO>>
    {
        private readonly IBaseRepositroy<User> _userRepository;
        private readonly IBaseRepositroy<UserRole> _userRoleRepository;
        private readonly IBaseRepositroy<Role> _roleRepository;
        private readonly ICaptchaService _captchaService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="userRoleRepository">用户角色仓储</param>
        /// <param name="roleRepository">角色仓储</param>
        /// <param name="captchaService">验证码服务</param>
        public RegisterUserCommandHandler(
            IBaseRepositroy<User> userRepository,
            IBaseRepositroy<UserRole> userRoleRepository,
            IBaseRepositroy<Role> roleRepository,
            ICaptchaService captchaService)
        {
            _userRepository = userRepository;
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
            _captchaService = captchaService;
        }

        /// <summary>
        /// 处理用户注册命令
        /// </summary>
        /// <param name="request">注册请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>注册结果</returns>
        public async Task<APIResult<UserDTO>> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证验证码
                var captchaResult = await _captchaService.VerifyCaptchaAsync(new CaptchaVerifyRequest
                {
                    CaptchaId = request.CaptchaId,
                    CaptchaCode = request.CaptchaCode
                });

                if (!captchaResult.IsValid)
                {
                    return new APIResult<UserDTO>
                    {
                        Code = ResultCode.添加失败,
                        Message = captchaResult.Message
                    };
                }

                // 验证用户名是否已存在
                var existingUser = await _userRepository
                    .FirstOrDefaultAsync(u => u.Username == request.Username)
                    .FirstOrDefaultAsync(cancellationToken);

                if (existingUser != null)
                {
                    return new APIResult<UserDTO>
                    {
                        Code = ResultCode.添加失败,
                        Message = $"用户名'{request.Username}'已存在，请使用其他用户名"
                    };
                }

                // 验证角色是否存在
                var role = await _roleRepository
                    .FirstOrDefaultAsync(r => r.RoleId == request.RoleId)
                    .FirstOrDefaultAsync(cancellationToken);

                if (role == null)
                {
                    return new APIResult<UserDTO>
                    {
                        Code = ResultCode.添加失败,
                        Message = $"角色ID为{request.RoleId}的角色不存在"
                    };
                }

                // 创建新用户
                var user = new User
                {
                    // 不手动设置UserId，让数据库自动生成
                    Username = request.Username,
                    Password = request.Password, // 实际应用中应该对密码进行哈希处理
                    RealName = request.RealName ?? string.Empty, // 确保RealName不为null
                    Status = 1 // 默认启用
                };
                
                // 添加用户
                await _userRepository.AddAsync(user);
                
                // 获取生成的用户ID
                int userId = user.UserId;

                // 添加用户角色关系
                var userRole = new UserRole
                {
                    UserId = userId,
                    RoleId = request.RoleId
                };

                await _userRoleRepository.AddAsync(userRole);

                // 创建返回DTO
                var userDto = new UserDTO
                {
                    UserId = user.UserId,
                    Username = user.Username,
                    RealName = user.RealName,
                    RoleId = request.RoleId,
                    RoleName = role.RoleName,
                    Status = user.Status,
                    Password = null // 不返回密码
                };

                // 返回成功结果
                return new APIResult<UserDTO>
                {
                    Code = ResultCode.添加成功,
                    Message = "用户注册成功",
                    Data = userDto
                };
            }
            catch (Exception ex)
            {
                // 记录详细的异常信息
                Console.WriteLine($"用户注册异常详情: {ex.ToString()}");
                
                return new APIResult<UserDTO>
                {
                    Code = ResultCode.添加失败,
                    Message = $"用户注册失败: {ex.Message}. 内部异常: {ex.InnerException?.Message ?? "无"}"
                };
            }
        }
    }
} 